package xyz.yiui.servlet.user;

import com.alibaba.fastjson.JSONArray;
import com.mysql.cj.Constants;
import com.mysql.cj.util.StringUtils;
import xyz.yiui.pojo.Role;
import xyz.yiui.pojo.User;
import xyz.yiui.service.role.RoleService;
import xyz.yiui.service.role.RoleServiceImpl;
import xyz.yiui.service.user.UserService;
import xyz.yiui.service.user.UserServiceImpl;
import xyz.yiui.util.Constans;
import xyz.yiui.util.PageSupport;

import javax.jws.soap.SOAPBinding;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

public class UserServlet extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        String method=req.getParameter("method");
        if(method.equals("savepwd")&&method!=null){
            this.updatePwd(req,resp);
        }else if(method.equals("pwdmodify")&&method!=null){
            this.pwdmodify(req,resp);
        }else if(method.equals("query")&&method!=null){
            this.query(req,resp);
        }else if(method != null && method.equals("add")){
            //增加操作
            this.add(req, resp);
        }else if(method != null && method.equals("deluser")){
            this.delUser(req, resp);
        }else if(method != null && method.equals("view")){
            this.getUserById(req, resp,"userview.jsp");
        }else if(method != null && method.equals("modify")){
            this.getUserById(req, resp,"usermodify.jsp");
        }else if(method != null && method.equals("modifyexe")){
            this.modify(req, resp);
        }else if(method != null && method.equals("getrolelist")){
            this.getRoleList(req,resp);
        }else if(method != null && method.equals("ucexist")){
            this.userCodeExist(req,resp);
        }

    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        doGet(req, resp);
    }
    ///修改密码
    public  void updatePwd(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        //从session里拿到当前登录用户的id
        Object o=req.getSession().getAttribute(Constans.USER_SESSION);
        ///拿到新密码
        String newpassword=req.getParameter("newpassword");
        System.out.println("UserServlet"+newpassword);
        boolean flag=false;
        if(o!=null && !StringUtils.isNullOrEmpty(newpassword)){
            UserService userService=new UserServiceImpl();
            flag=userService.updatePwd( ((User)o).getId(),newpassword );
            if(flag){//提示修改成功，并且移除当前session
                req.setAttribute("message","update success,please logout");
                System.out.println("update success,please logout");
                req.getSession().removeAttribute(Constans.USER_SESSION);
            }
            else{
                req.setAttribute("message","update failed");
                System.out.println("update failed");
            }
        }
        else{
            req.setAttribute("message","newpassword wrong");
            System.out.println("newpassword wrong");
        }
        req.getRequestDispatcher("pwdmodify.jsp").forward(req,resp);
        System.out.println("update suceess");
    }
    ///判断旧密码是否合法,session里就有用户的密码，无需查询数据库
    public void pwdmodify(HttpServletRequest req, HttpServletResponse resp){
        //从session里拿id
        Object o=req.getSession().getAttribute(Constans.USER_SESSION);
        String oldpassword=req.getParameter("oldpassword");///跟Ajax里的保持一致
        ///万能的map存放结果集
        Map<String,String> resultMap=new HashMap<String,String>();
        if(o==null){
            ///session失效或是过期了
            resultMap.put("result","sessionerror");
        }else if(StringUtils.isNullOrEmpty(oldpassword)){
            ///输入的密码为空
            resultMap.put("result","error");
        }
        else{
            ///得到session里用户的密码
            String userpwd=((User)o).getUserPassword();
            if(oldpassword.equals(userpwd)){
                ///密码正确
                resultMap.put("result","true");
            }
            else{
                resultMap.put("result","false");///密码不正确
            }
        }
        ///将map转为json
        /*map=["result","true"]
        * json={key:value}
        * */
        try{
            resp.setContentType("application/json");//设置响应格式
            PrintWriter writer=resp.getWriter();
            writer.write(JSONArray.toJSONString(resultMap));
            writer.flush();///刷新
            writer.close();//关闭 防止内存溢出
        }catch (IOException e){
            e.printStackTrace();
        }

    }

    ///查询所有用户
    public void query(HttpServletRequest req,HttpServletResponse resp) throws ServletException, IOException {
        //查询用户列表
        //获取前端数据
        String queryUserName=req.getParameter("queryname");
        String tmp=req.getParameter("queryUserRole");///临时变量
        String pageIndex=req.getParameter("pageIndex");
        int queryUserRole=0;

        //获取用户列表
        UserServiceImpl userService=new UserServiceImpl();
        RoleServiceImpl roleService=new RoleServiceImpl();
        ///第一次走这个请求，一定是第一页，假设页面大小是固定的
        int pageSize=Constans.PAGESIZE;
        int currentPageNo=1;//当前

        if(queryUserName==null){
            queryUserName="";
        }
        System.out.println(tmp);
        System.out.println(queryUserRole);
        if(!StringUtils.isNullOrEmpty(tmp)){
            queryUserRole= Integer.parseInt(tmp);///查询真正的值
            System.out.println(queryUserRole);
        }

        if(pageIndex!=null){
            currentPageNo=Integer.parseInt(pageIndex);
        }
        //获取用户的总数(分页，上一页和下一页)
        int totalCount=userService.getUserCount(queryUserName,queryUserRole);
        //总页数支持
        PageSupport pageSupport=new PageSupport();
        pageSupport.setCurrentPageNo(currentPageNo);
        pageSupport.setPageSize(pageSize);
        pageSupport.setTotalCount(totalCount);
        int totalPageCount=pageSupport.getTotalPageCount();///得到总页数

        //下面控制首页和尾页
        if(currentPageNo<1) currentPageNo=1;
        if(currentPageNo>totalPageCount) currentPageNo=totalPageCount;

        ///获取用户列表展示 将数据给前端
        List<User> userList=userService.getUserList(queryUserName,queryUserRole,currentPageNo,pageSize);
        req.setAttribute("userList",userList);
        List<Role>roleList=roleService.getRoleList();
        req.setAttribute("roleList",roleList);
        req.setAttribute("totalCount",totalCount);
        req.setAttribute("currentPageNo",currentPageNo);
        req.setAttribute("totalPageCount",totalPageCount);
        req.setAttribute("queryUserName",queryUserName);
        req.setAttribute("queryUserRole",queryUserRole);

        //返回前端
        try{
            req.getRequestDispatcher("userlist.jsp").forward(req,resp);
        }catch (Exception e){
            e.printStackTrace();
        }


    }

    //增加新用户
    private void add(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        System.out.println("add()================");
        String userCode = request.getParameter("userCode");
        String userName = request.getParameter("userName");
        String userPassword = request.getParameter("userPassword");
        String gender = request.getParameter("gender");
        String birthday = request.getParameter("birthday");
        String phone = request.getParameter("phone");
        String address = request.getParameter("address");
        String userRole = request.getParameter("userRole");

        User user = new User();
        user.setUserCode(userCode);
        user.setUserName(userName);
        user.setUserPassword(userPassword);
        user.setAddress(address);
        try {
            user.setBirthday(new SimpleDateFormat("yyyy-MM-dd").parse(birthday));
        } catch (ParseException e) {
            e.printStackTrace();
        }
        user.setGender(Integer.valueOf(gender));
        user.setPhone(phone);
        user.setUserRole(Integer.valueOf(userRole));
        user.setCreationDate(new Date());
        user.setCreatedBy(((User)request.getSession().getAttribute(Constans.USER_SESSION)).getId());

        UserService userService = new UserServiceImpl();
        if(userService.add(user)){
            response.sendRedirect(request.getContextPath()+"/jsp/user.do?method=query");
        }else{
            request.getRequestDispatcher("useradd.jsp").forward(request, response);
        }
    }
    //删除用户
    private void delUser(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        String id = request.getParameter("uid");
        Integer delId = 0;
        try{
            delId = Integer.parseInt(id);
        }catch (Exception e) {
            delId = 0;
        }
        HashMap<String, String> resultMap = new HashMap<String, String>();
        if(delId <= 0){
            resultMap.put("delResult", "notexist");
        }else{
            UserService userService = new UserServiceImpl();
            if(userService.deleteUserById(delId)){
                resultMap.put("delResult", "true");
            }else{
                resultMap.put("delResult", "false");
            }
        }
        //把resultMap转换成json对象输出
        response.setContentType("application/json");
        PrintWriter outPrintWriter = response.getWriter();
        outPrintWriter.write(JSONArray.toJSONString(resultMap));
        outPrintWriter.flush();
        outPrintWriter.close();
    }
    //根据id得到用户
    private void getUserById(HttpServletRequest request, HttpServletResponse response,String url)
            throws ServletException, IOException {
        String id = request.getParameter("uid");
        if(!StringUtils.isNullOrEmpty(id)){
            //调用后台方法得到user对象
            UserService userService = new UserServiceImpl();
            User user = userService.getUserById(id);
            request.setAttribute("user", user);
            request.getRequestDispatcher(url).forward(request, response);
        }
    }
    //更新用户
    private void modify(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        String id = request.getParameter("uid");
        String userName = request.getParameter("userName");
        String gender = request.getParameter("gender");
        String birthday = request.getParameter("birthday");
        String phone = request.getParameter("phone");
        String address = request.getParameter("address");
        String userRole = request.getParameter("userRole");

        User user = new User();
        user.setId(Integer.valueOf(id));
        user.setUserName(userName);
        user.setGender(Integer.valueOf(gender));
        try {
            user.setBirthday(new SimpleDateFormat("yyyy-MM-dd").parse(birthday));
        } catch (ParseException e) {
            e.printStackTrace();
        }
        user.setPhone(phone);
        user.setAddress(address);
        user.setUserRole(Integer.valueOf(userRole));
        user.setModifyBy(((User)request.getSession().getAttribute(Constans.USER_SESSION)).getId());
        user.setModifyDate(new Date());

        UserService userService = new UserServiceImpl();
        if(userService.modify(user)){
            response.sendRedirect(request.getContextPath()+"/jsp/user.do?method=query");
        }else{
            request.getRequestDispatcher("usermodify.jsp").forward(request, response);
        }

    }
    //得到角色列表
    private void getRoleList(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        List<Role> roleList = null;
        RoleService roleService = new RoleServiceImpl();
        roleList = roleService.getRoleList();
        //把roleList转换成json对象输出
        response.setContentType("application/json");
        PrintWriter outPrintWriter = response.getWriter();
        outPrintWriter.write(JSONArray.toJSONString(roleList));
        outPrintWriter.flush();
        outPrintWriter.close();
    }
    ///判断用户编码的用户是否存在
    private void userCodeExist(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        String userCode = request.getParameter("userCode");
        HashMap<String, String> resultMap = new HashMap<String, String>();
        if(StringUtils.isNullOrEmpty(userCode)){
            resultMap.put("userCode", "exist");
        }else{
            UserService userService = new UserServiceImpl();
            User user = userService.selectUserCodeExist(userCode);
            if(null != user){
                resultMap.put("userCode","exist");
            }else{
                resultMap.put("userCode", "notexist");
            }
        }
        //把resultMap转为json字符串以json的形式输出
        //配置上下文的输出类型
        response.setContentType("application/json");
        //从response对象中获取往外输出的writer对象
        PrintWriter outPrintWriter = response.getWriter();
        //把resultMap转为json字符串 输出
        outPrintWriter.write(JSONArray.toJSONString(resultMap));
        outPrintWriter.flush();//刷新
        outPrintWriter.close();//关闭流
    }



}















